/*
 *
 *  Copyright (C) 2008 GSyC/LibreSoft
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author : Roberto Calvo Palomino <rocapal@gsyc.es>
 *
 */


package com.LibreGeoSocial.App;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.LibreGeoSocial.Api.LibreGeoSocial;
import com.LibreGeoSocial.Api.User;
import com.LibreGeoSocial.App.Utils.FacebookHandler;
import com.LibreGeoSocial.App.Utils.MD5Sum;



public class LibreGeoSocialApp extends Activity implements Runnable, OnClickListener {
	
	private static final String TAG 		= "LibreGeoSocialApp";
	
    private static final int MENU_REGISTER = Menu.FIRST + 1;
    
    public static String KEY_USERNAME  = "APP_username";
    public static String KEY_PASSWORD  = "APP_password";


	
	private static List<String> contactList;
	
	private ProgressDialog pd;
	 
    ImageView fBook;
	Button btLogin;
	Button btRegister; 
	CheckBox cbFaceBook, cbAutologin, cbPassword;
	
	TextView txtUser;
	TextView txtPasswd;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        txtUser = (TextView) this.findViewById(R.id.txtLogin);
        txtPasswd = (TextView) this.findViewById(R.id.txtPass);
        Log.i("INICIO","------------------------------------------------AQUI EMPIEZA-------------------------------");
        btLogin = (Button)this.findViewById(R.id.btLogin); 
        btLogin.setOnClickListener(this);
        
        btRegister = (Button)this.findViewById(R.id.btRegister); 
        btRegister.setOnClickListener(this);

        fBook = (ImageView)this.findViewById(R.id.imgFacebook); 
        fBook.setImageResource(R.drawable.facebook);
        cbPassword = (CheckBox)  this.findViewById(R.id.CB_Password);
        cbFaceBook = (CheckBox)  this.findViewById(R.id.CB_Facebook);
        cbAutologin = (CheckBox)  this.findViewById(R.id.CB_Autologin);
        cbAutologin.setEnabled(false);
        
        Intent i = getIntent();
        if (!((i.toString()).contains("act=android.intent.action.MAIN")))
        {
        	SharedPreferences sharedPreferences = 
				PreferenceManager.getDefaultSharedPreferences(LibreGeoSocialApp.this);
        	Editor edit = sharedPreferences.edit();
        	edit.putBoolean(LGS_Preferences.KEY_APP_AUTOLOGIN, false);
			cbAutologin.setChecked(false);
			edit.commit();
        }
        
        cbPassword.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
        	{
        		cbAutologin.setEnabled(isChecked);
        		SharedPreferences sharedPreferences = 
					PreferenceManager.getDefaultSharedPreferences(LibreGeoSocialApp.this);
				Editor edit = sharedPreferences.edit();
				edit.putBoolean(LGS_Preferences.KEY_APP_PASSWORD, isChecked);
				if (!isChecked)
				{
					edit.putBoolean(LGS_Preferences.KEY_APP_AUTOLOGIN, false);
					cbAutologin.setChecked(false);
				}	
				edit.commit();
        	}
        });
        
        
        
        cbAutologin.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				SharedPreferences sharedPreferences = 
					PreferenceManager.getDefaultSharedPreferences(LibreGeoSocialApp.this);
				Editor edit = sharedPreferences.edit();
				edit.putBoolean(LGS_Preferences.KEY_APP_AUTOLOGIN, isChecked);
				edit.commit();
			}
		});
        
        loadConfig();
        
        LibreGeoSocial.getInstance().setUrl(getString(R.string.urlServer));
        LibreGeoSocial.getInstance().setFormat("JSON");

        if ( (txtUser.getText().length() >0) && (txtPasswd.getText().length()>0)  )
        {
        	Log.e("LGS","login y pass lleno");
        	//Login automatically
        	SharedPreferences sharedPreferences = 
				PreferenceManager.getDefaultSharedPreferences(this);
        	
        	if(sharedPreferences.getBoolean(LGS_Preferences.KEY_APP_AUTOLOGIN, false)){
        		cbAutologin.setChecked(true);
        		doLogin();
        	}
        }
        else
        {
        	Log.e("LGS","login y pass vacio");
        }
        
    }
    
    private void doLogin()
    {
    	final Thread thread = new Thread(this);
    	
    	DialogInterface.OnCancelListener dialogCancel = new DialogInterface.OnCancelListener() {

            public void onCancel(DialogInterface dialog) {
            	
            	thread.stop();
            }
          
        };
    	
		pd = ProgressDialog.show(this, this.getResources().getString(R.string.login), 
				this.getResources().getString(R.string.login_msg), true, true, dialogCancel);
		
		
		thread.start();

    	
    }
    
    private void loadConfig()
    {
    	
    	SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		
		Editor editor = sharedPreferences.edit();
		if(sharedPreferences.getBoolean(LGS_Preferences.KEY_APP_PASSWORD, false))
		{
			cbPassword.setChecked(true);
			// Username 
			String username = sharedPreferences.getString(KEY_USERNAME, null);
		
			if (username != null)			
				txtUser.setText(username);	
		
		
			// Password 
			String password = sharedPreferences.getString(KEY_PASSWORD, null);
		
			if (password != null)			
				txtPasswd.setText(password);	
		}	
    }
    
    private void saveConfig ()
    {
    	
    	SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		
		Editor editor = sharedPreferences.edit();
		
		editor.putString(KEY_USERNAME, txtUser.getText().toString());
		editor.putString(KEY_PASSWORD, txtPasswd.getText().toString());
		
		editor.commit();
    }
    
    public void onClick(View v) {

        String login = "";
        String password = "";

        if ( btLogin.isPressed() ) 
        {

        	if (cbFaceBook.isChecked())
        	{
        		FacebookHandler myFB = new FacebookHandler( txtUser.getText().toString(),
        													txtPasswd.getText().toString());

        		if (myFB.connect())
        		{

        			String md5Pass = MD5Sum.md5Sum(txtPasswd.getText().toString());

        			User user = new User(0, txtUser.getText().toString(),
                                                        "(FB)",
                                                        txtUser.getText().toString(),
                                                        txtUser.getText().toString(),
                                                        "",0.0, 0.0, 0.0, 0.0, "",
                                                        "ES",
                                                        00000,
                                                        "2000-01-01",
                                                        null,null,null);

        			user.setPassword(md5Pass);

        			LibreGeoSocial.getInstance().registerUser(user);

        			login = txtUser.getText().toString();
        			password = md5Pass;


        		}
        		else
        		{
        			Toast.makeText(getBaseContext(),
        						"Error: The system could not login in Facebook!",
        						Toast.LENGTH_LONG).show();

        			return;
        		}

        	}
        	else
        	{
        		login = txtUser.getText().toString();
        		password = txtPasswd.getText().toString();
        	}

        	boolean isLogin = LibreGeoSocial.getInstance().login( login, password);

        	if (isLogin)
        	{
                    saveConfig();                    
                    goScreenHome();
            }
            else
            {

            	Toast.makeText(getBaseContext(),
            				"Error: " + LibreGeoSocial.getInstance().getLastMsgServer(),
            				Toast.LENGTH_LONG).show();

            }

        }
        else if (btRegister.isPressed())
    	{
            Intent i = new Intent(this,Register.class);
            startActivity(i);
    	}

    }
    	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	
        super.onCreateOptionsMenu(menu);
        menu.add(0, MENU_REGISTER, 0, "Register")
        		.setIcon(R.drawable.register)
                .setAlphabeticShortcut('A');
        
    
        
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected (MenuItem item) {
    	
    	switch (item.getItemId()) {
    	
    	case MENU_REGISTER:
    		
    		Intent i = new Intent(this,Register.class);
        	startActivity(i); 
        	
    		break;

        }
        return super.onOptionsItemSelected(item);
    }
   

	public void run() {
		
    	boolean isLogin = LibreGeoSocial.getInstance().login( txtUser.getText().toString()	, txtPasswd.getText().toString() );

    	if (isLogin)    	               
    		handler.sendEmptyMessage(0);            	

		
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {			
			goScreenHome();
			//pd.dismiss();	
		}
	};
	
	private void goScreenHome()
	{
        Intent i = new Intent(this,GeoSocialTab.class);
        startActivity(i);
        this.finish();
	}



}

